import base64
import datetime
import hashlib
import json
import re
import time
import urllib.parse
import execjs
import requests
import logging

from config import Config


class Cookies(object):
    ip = ''
    proxyAuth = ''

    def get_hash256(self, data: str):
        hash256 = hashlib.sha256(data.encode('utf-8'))
        return hash256.hexdigest()

    def get_hashsha1(self, data: str):
        sha = hashlib.sha1(data.encode('utf-8'))
        return sha.hexdigest()

    def get_hashmd5(self, data: str):
        hl = hashlib.md5(data.encode('utf-8'))
        return hl.hexdigest()

    def process_ip(self):

        if self.ip:
            url = "http://www.gsxt.gov.cn/index.html"
            proxies = {"http": f"http://{self.ip}"}
            headers = {"User-Agent": "Mozilla/5.0"}
            headers['Proxy-Authorization'] = self.proxyAuth
            try:
                res = requests.get(url, proxies=proxies, headers=headers, timeout=(10, 20))
                if res.status_code in(200,521) and str(res.status_code).startswith('4', 0) == False:
                    logging.info(f'本次复用IP地址为：{self.ip}')
                    return 'http://' + self.ip, self.proxyAuth
                else:
                    self.ip = ''
                    return self.process_ip()
            except Exception as e:
                logging.error(e, exc_info=True)
                self.ip = ''
                return self.process_ip()
        else:
            proxyUser = Config.ProxyUser
            proxyPass = Config.ProxyPass
            proxy = Config.Proxy
            self.proxyAuth = "Basic " + base64.urlsafe_b64encode(bytes((proxyUser + ":" + proxyPass), "ascii")).decode(
                "utf8")
            try:
                proxy_ip = requests.get(proxy).text
                logging.info(f'代理响应：{proxy_ip}')
                respone = json.loads(proxy_ip)
                if respone['code'] == 0:
                    self.ip = respone['data']['proxy_list'][0]
                    logging.info(f'本次IP地址为：{self.ip}')
                    return 'http://' + self.ip, self.proxyAuth
                    # return 'http://36.6.57.162:21771',proxyAuth
                else:
                    raise Exception(f'代理返回异常{respone}')
            except Exception as e:
                logging.error(e, exc_info=True)

    def get_cookies(self):
        data = []
        headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Host': 'www.gsxt.gov.cn',
            'Proxy-Connection': 'keep-alive',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36',
        }
        try:
            url1 = 'http://www.gsxt.gov.cn/index.html'
            process = self.process_ip()
            proxies = {'http': process[0]}
            headers['Proxy-Authorization'] = process[1]
            r1 = requests.get(url1, headers=headers, proxies=proxies, verify=False, timeout=(5, 10))
            js = r1.text
            print(f"JS:{js}")
            js = js.replace('<script>document.cookie=', '').replace(
                ';location.href=location.pathname+location.search</script>',
                '')
            result = execjs.eval(js)
            __jsluid_h = r1.headers['Set-Cookie']
            __jsl_clearance = result
            cookies = {
                '__jsluid_h': __jsluid_h.replace('__jsluid_h=', ''),
                '__jsl_clearance': __jsl_clearance.replace('__jsl_clearance=', '')
            }
            url2 = 'http://www.gsxt.gov.cn/index.html'
            r2 = requests.get(url2, headers=headers, proxies=proxies, verify=False, cookies=cookies, timeout=(5, 10))
            js_pre = """
            var document = {};
            var location = {pathname:"pathname", search:"search"};
            function getCookie(func, time){
                func();
            };
            """
            js_str = js_pre + re.findall('<script>(.+?)</script>', r2.text)[0]
            # 删除检测浏览器相关代码, 也可以不删除, 补相关环境即可
            replace_str = re.findall(r'function go.+?var .{7,10}=.{7,10};(.+?)var .{7,10}=new Date', r2.text)[0]
            js_str = js_str.replace(replace_str, '')
            # node里面执行setTimeout失败, 替换该函数为自定义的函数
            js_str = js_str.replace('setTimeout', 'getCookie')
            ctx = execjs.compile(js_str)
            __jsl_clearance = ctx.eval('document.cookie')
            __jsl_clearance = re.findall('__jsl_clearance=(.+?);Max', __jsl_clearance)[0]
            # s.cookies.set('__jsl_clearance', __jsl_clearance)  # 更新cookie到session中
            # print('更新cookie成功:', __jsl_clearance)
            cookies1 = {
                '__jsluid_h': __jsluid_h.replace('__jsluid_h=', ''),
                '__jsl_clearance': __jsl_clearance,
            }
            url3 = 'http://www.gsxt.gov.cn/index.html'
            r3 = requests.get(url3, headers=headers, proxies=proxies, verify=False, cookies=cookies1, timeout=(5, 10))
            r3cookies = r3.headers['Set-Cookie']
            r3cookies = r3cookies.split(',')
            JSESSIONID = ''
            SECTOKEN = ''
            tlb_cookie = ''
            for i in r3cookies:
                if 'JSESSIONID' in i:
                    JSESSIONID = i.replace('JSESSIONID=', '').strip()
                if 'SECTOKEN' in i:
                    SECTOKEN = i.replace('SECTOKEN=', '').strip()
                if 'tlb_cookie' in i:
                    tlb_cookie = i.replace('tlb_cookie=', '').strip()
            # cookies2为取数据所需要的cookie
            cookies2 = {
                '__jsluid_h': __jsluid_h.replace('__jsluid_h=', ''),
                '__jsl_clearance': __jsl_clearance,
                'JSESSIONID': JSESSIONID,
                'SECTOKEN': SECTOKEN,
                'tlb_cookie': tlb_cookie,
            }
            # data.append(cookies2)
            # data.append(proxies)
            # data.append(process[1])
            data.extend([cookies2, proxies, process[1]])
            return data
        except Exception as e:
            logging.error(e, exc_info=True)
            return data
